package org.myspringframework.aop;

import org.aopalliance.intercept.MethodInterceptor;
import org.myspringframework.aop.framework.adapter.DefaultAdvisorAdapterRegistry;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//通知链工厂
public class DefaultAdvisorChainFactory implements AdvisorChainFactory{

    ////根据advisor切面生成对应方法的通知链
    @Override
    public List<Object> getInterceptorsAndDynamicInterceptionAdvice(AdvisedSupport advicedSupport, Method method, Class<?> targetClass) throws Exception {
        //获取advisors切面
        List<Advisor> advisors = advicedSupport.getAdvisors();
        List<Object> interceptorList = new ArrayList(advisors.size());
        DefaultAdvisorAdapterRegistry registry = new DefaultAdvisorAdapterRegistry();

        //遍历advisor切面进行匹配
        for (Advisor advisor : advisors) {
            if (advisor instanceof PointcutAdvisor){
                PointcutAdvisor pointcutAdvisor=(PointcutAdvisor) advisor;
                //先进行class匹配
                if (pointcutAdvisor.getPointcut().getClassFilter().matches(targetClass)){
                    //再进行method匹配
                    if(pointcutAdvisor.getPointcut().getMethodMatcher().matches(method,targetClass)){
                        //匹配成功
                        MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
                        interceptorList.addAll(Arrays.asList(interceptors));
                    }
                }
            }
        }
        return interceptorList;
    }
}
